import win32evtlog
import win32evtlogutil
import win32con
from datetime import datetime, timedelta
import re
from datetime import datetime, timedelta
import logger

class mSysEvent():
    def __init__(self):
        self.flag = 0
        self.log = logger.logger_config(log_path='sys.log', logging_name='sys日志')

    def get_log_time(self,msg):
        # 给定的字符串
        log_entry = msg

        # 使用正则表达式提取时间字符串
        time_strings = re.findall(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}Z', log_entry)

        # 去掉"T"和秒数之后的小数点时间，只保留日期和时间的整数部分
        time_strings_without_decimal = [time_str.replace('T', ' ').split('.')[0] for time_str in time_strings]

        # 将处理后的时间字符串转换为datetime对象
        datetime_objects = [datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S') for time_str in time_strings_without_decimal]

        # 比较两个时间对象
        if len(datetime_objects) >= 2:
            time_new = datetime_objects[0]
            time_old = datetime_objects[1]
            time_difference = time_old - time_new
            
            return time_old,time_difference,time_new
        else:
            print("Not enough time strings found in the log entry.")


    def sysTime_is_modified(self):
        # 打开系统日志
        handle = win32evtlog.OpenEventLog(None, 'System')

        # 设置查询的时间范围为最近一个星期
        one_week_ago = datetime.now() - timedelta(hours=2)
        end_time = datetime.now()

        # 将时间转换为可以用于比较的格式
        one_week_ago_filetime = one_week_ago.replace(microsecond=0).timestamp()
        end_time_filetime = end_time.replace(microsecond=0).timestamp()

        flag = 0
        # 循环读取日志
        while True:
            events = win32evtlog.ReadEventLog(handle,
                                                win32evtlog.EVENTLOG_BACKWARDS_READ |
                                                win32evtlog.EVENTLOG_SEQUENTIAL_READ,
                                                0)
            if not events:
                break
            # print('1111111111111')
            for event in events:
                        # 检查事件来源是否为'Microsoft-Windows-Kernel-General'
                        if event.SourceName and event.SourceName.startswith('Microsoft-Windows-Kernel-General'):
                            # print('222222')
                            # 获取事件的描述信息
                            if event.EventID == 1:  # 系统时间更改事件的事件ID
                                message = win32evtlogutil.SafeFormatMessage(event, handle)
                                old_time,b,c = self.get_log_time(message)
                                # print('3333333')
                                # self.log.info(f"OldTime333: {old_time + timedelta(hours=8)}")
                                # self.log.info(f"2hours_ago: {one_week_ago}")
                                if (old_time + timedelta(hours=8)).timestamp() >= one_week_ago_filetime:
                                    message = win32evtlogutil.SafeFormatMessage(event, handle)
                                    # print(f"Event ID: {event.EventID}, Time: {event.TimeGenerated}, Message: {message}")
                                    old_time_,time_difference,new_time_ = self.get_log_time(message)
                                    # print('4444444')
                                    # 检查时间差异是否超过1小时
                                    if time_difference >= timedelta(hours=1):
                                        self.log.info(f"NewTime: {new_time_}")
                                        self.log.info(f"OldTime: {old_time_}")
                                        # self.log.info(f"Time difference: {time_difference}")
                                        # self.log.error("error：检测到修改系统时间")
                                        self.flag = 1
                                        # print('6666666')
        # 关闭日志句柄
        win32evtlog.CloseEventLog(handle)
        return self.flag

if __name__ == '__main__':
    m = mSysEvent()
    if m.sysTime_is_modified():
        print('已修改')
